//
//  BaseTabBarController.m
//  Custom_Weibo
//
//  Created by LEO on 12/7/15.
//  Copyright © 2015 Leo_Lei. All rights reserved.
//

#import "BaseTabBarController.h"
#import "AppDelegate.h"

@implementation BaseTabBarController {
    ThemeImageView *_tabBGImageView;
    ThemeImageView *_tabSelectedImageView;
    
    ThemeImageView *_badgeView;
    ThemeLabel *_badgeLabel;
}

#pragma mark - SYSTEM_METHOD
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self loadControllers];
    [self customTabBar];
    
    [NSTimer scheduledTimerWithTimeInterval:3
                                     target:self
                                   selector:@selector(regularGetData:)
                                   userInfo:nil
                                    repeats:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - TIME_INTERVAL
- (void)regularGetData:(NSTimer *)timer {
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    SinaWeibo *sinaWeibo = delegate.sinaWeibo;
    
    [sinaWeibo requestWithURL:kUnread_Count
                       params:nil
                   httpMethod:@"GET"
                     delegate:self];
}

- (void)request:(SinaWeiboRequest *)request didFailWithError:(NSError *)error {
    NSLog(@"Request Error:%@", error);
}

- (void)request:(SinaWeiboRequest *)request didFinishLoadingWithResult:(id)result {
    if (_badgeView == nil) {
        CGRect badgeFrame = CGRectMake(kBottomButtonWidth - kBadgeViewSidelength, 0,
                                       kBadgeViewSidelength, kBadgeViewSidelength);
        _badgeView = [[ThemeImageView alloc] initWithFrame:badgeFrame];
        _badgeView.imageName = @"number_notify_9";
        [self.tabBar addSubview:_badgeView];
        
        _badgeLabel = [[ThemeLabel alloc] initWithFrame:_badgeView.bounds];
        _badgeLabel.textAlignment = NSTextAlignmentCenter;
        _badgeLabel.backgroundColor = [UIColor clearColor];
        _badgeLabel.font = [UIFont systemFontOfSize:13];
        _badgeLabel.colorName = @"Timeline_Notice_color";
        [_badgeView addSubview:_badgeLabel];
    }
    
    NSNumber *status = result[@"status"];
    NSInteger count = [status integerValue];
    if (count > 0) {
        _badgeView.hidden = NO;
        if (count > 99) {
            _badgeLabel.text = @"99+";
        }else {
            _badgeLabel.text = [NSString stringWithFormat:@"%li", count];
        }
    }else {
        _badgeView.hidden = YES;
    }
}

#pragma mark - TABBAR_CONTROLLER
- (void)loadControllers {
    /*  Set five view controllers to manager each view, and use navigation 
     controller to control them all.
     */
    NSArray *names = @[@"Home", @"Message", @"Profile", @"Discovery", @"More"];
    NSMutableArray *Controllers = [[NSMutableArray alloc] init];
    
    for (NSString *name in names) {
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:name bundle:nil];
        UINavigationController *navigationController = [storyBoard instantiateInitialViewController];
        /*  You only see a view controller show on the screen, so the top view
         controller is the controller you create.
         */
        navigationController.topViewController.title = name;
        [Controllers addObject:navigationController];
    }
    self.viewControllers = Controllers;
}

#pragma mark RECREATE_TAB_BAR
- (void)customTabBar {
    /*  Once you wanna use custom tab bar, remove the original button, and then, 
     you can add custom button on your own.
     */
    for (UIView *view in self.tabBar.subviews) {
        Class cls = NSClassFromString(@"UITabBarButton");
        if ([view isKindOfClass:cls]) {
            [view removeFromSuperview];
        }
    }
    
    //  To distinguish custom buttons, add different images on them.
    CGRect BGFrame = CGRectMake(0, 0, kScreenWidth, kBottomButtonHeight);
    _tabBGImageView = [[ThemeImageView alloc] initWithFrame:BGFrame];
    _tabBGImageView.imageName = @"mask_navbar.png";
    [self.tabBar addSubview:_tabBGImageView];
    
    NSArray *imageNames = @[
                            @"home_tab_icon_1.png",
                            @"home_tab_icon_2.png",
                            @"home_tab_icon_3.png",
                            @"home_tab_icon_4.png",
                            @"home_tab_icon_5.png"
                            ];
    
    //  Add some marvellous effects when selected a button.
    CGRect selectedFrame = CGRectMake(0, 0, kBottomButtonWidth, kBottomButtonHeight);
    _tabSelectedImageView = [[ThemeImageView alloc] initWithFrame:selectedFrame];
    _tabSelectedImageView.imageName = @"home_bottom_tab_arrow.png";
    [self.tabBar addSubview:_tabSelectedImageView];
    
    //  After the preparation work is done, finally add the buttons.
    for (int i = 0; i < kBottomButtonCount; i++) {
        NSString *name = imageNames[i];
        CGRect ButtonFrame = CGRectMake(i * kBottomButtonWidth, 0,
                                        kBottomButtonWidth, kBottomButtonHeight);
        
        /*  Cause you wanna use different buttons when theme is changed, you 
         need create a custom button class to do that.
         */
        ThemeButton *button = [[ThemeButton alloc] initWithFrame:ButtonFrame];
        button.defalutImageName = name;
        button.highlightedImageName = @"button_icon_OK";
        button.frame = ButtonFrame;
        button.tag = i;
        [button addTarget:self
                   action:@selector(buttonClick:)
         forControlEvents:UIControlEventTouchUpInside];
        
        [self.tabBar addSubview:button];
        
        /*  When you don't touch any button, make sure the selected image is on 
         the first one button.
         */
        if (i == 0) {
            _tabSelectedImageView.center = button.center;
        }
    }
}

#pragma mark - SWITCH_SELECTED_IMAGE
- (void)buttonClick:(ThemeButton *)button {
    self.selectedIndex = button.tag;
    
    [UIView animateWithDuration:0.2 animations:^{
        _tabSelectedImageView.center = button.center;
    }];
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
